<template>
  <div class="life-container">
    <div class="tree-box">
      <el-tree
        ref="tree"
        :data="columnData"
        :props="defaultProps"
        :check-strictly="true"
        show-checkbox
        @node-expand="handleNodeExpand"
        @node-collapse="handleNodeCollapse"
      >
        <!-- eslint-disable-next-line -->
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <span>
            <i
              v-if="data.children && data.children.length>0"
              :class="(!data.icon || data.icon === 'el-icon-folder') ? 'el-icon-folder' : 'el-icon-folder-opened'"
              style="padding-right:5px;"
            />
            <i v-else />{{ node.label }} {{ node.icon }}
          </span>
        </span>
      </el-tree>
    </div>
    <div class="opertions">
      <div class="input-box">
        <el-button type="primary" class="btn" circle icon="el-icon-thumb" @click="getSelectNode" />
      </div>
    </div>
    <div class="echarts">
      <div class="top">
        <div ref="sumChart" class="sum-chart" />
      </div>
      <div class="bottom">
        <div ref="avgChart" class="avg-chart" />
      </div>
    </div>
    <div class="result">
      <el-collapse accordion>
        <el-collapse-item v-for="(item, index) in result" :key="index">
          <template slot="title">
            {{ item.title }}
          </template>
          <div class="course">课程总数：{{ item.sum }}</div>
          <div class="avg">①参课人数>平均值的课程数量：{{ item.over }}</div>
          <div class="next">②继续下一轮选课：{{ item.next }}</div>
          <div class="precent">①/②占比：{{ item.precent }}</div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
import { terminfoMap } from '@/utils/dictionary'
export default {
  data() {
    return {
      terminfoMap,
      columnData: [],
      num: '',
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      sumOptions: {
        xAxis: {
          data: []
        },
        yAxis: {},
        grid: {
          left: '2%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        tooltip: {},
        legend: {
          data: ['总数']
        },
        series: [{
          name: '总数',
          type: 'line',
          data: []
        }]
      },
      avgOptions: {
        xAxis: {
          data: [1, 2, 3, 4, 5, 6, 7, 8, 9]
        },
        yAxis: {},
        grid: {
          left: '2%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        tooltip: {},
        legend: {
          data: ['平均值']
        },
        series: [{
          name: '平均值',
          type: 'line',
          data: []
        }]
      },
      planStageData: {},
      avgChart: null,
      sumChart: null,
      result: [
        {
          title: '第一期',
          sum: 0,
          over: 0,
          next: 0,
          precent: 0
        }
      ],
      curIds: {}
    }
  },
  created() {
    this.getColumnTree()
  },
  mounted() {
    this.initSumChart()
    this.initAvgChart()
  },
  methods: {
    async getColumnTree() {
      const res = await this.$api.getColumnTree()
      if (res && res.code === 200) {
        this.columnData = this.recursionChangeTree(res.data.records)
      }
    },
    // 递归改变树状结构
    recursionChangeTree(tree) {
      if (Array.isArray(tree) && tree.length > 0) {
        return tree.map(item => {
          this.customId
          this.$set(item, 'title', item.channelName || item.categoryName)
          if (item.children && Array.isArray(item.children)) {
            this.recursionChangeTree(item.children)
          }
          return item
        })
      } else {
        return []
      }
    },
    async getSelectNode() {
      const nodes = this.$refs.tree.getCheckedNodes()
      if (nodes.length > 0) {
        const ids = nodes.map(item => item.categoryId)
        const res = await this.$api.getPlanStageData(ids.join(','))
        if (res && res.code === 200) {
          this.planStageData = res.data.stageObj
          this.calculateAvg()
          this.analyzeResult()
        }
      } else {
        this.$message.error('请勾选课程类别')
      }
    },
    // 计算平均值和总数和分析结果
    calculateAvg() {
      const avgArr = [] // 平均值
      const sumArr = [] // 总数
      const stageArr = [] // 期数
      this.result = []
      this.curIds = {}
      Object.keys(this.planStageData).forEach(key => {
        stageArr.push(terminfoMap[key - 1])
        const data = this.planStageData[key]
        const len = data.length
        const dict = {
          sum: len,
          title: terminfoMap[key - 1]
        }
        data.forEach(item => {
          if (sumArr[key - 1]) {
            sumArr[key - 1] += item.enrollCount
          } else {
            sumArr[key - 1] = item.enrollCount
          }
        })
        const avg = sumArr[key - 1] / len
        avgArr[key - 1] = avg
        let count = 0
        data.forEach(item => {
          if (item.enrollCount >= avg) {
            count++
            if (!this.curIds[key]) {
              this.curIds[key] = [item.courseId]
            } else {
              this.curIds[key].push(item.courseId)
            }
          }
        })
        dict.over = count
        this.result.push(dict)
      })
      this.sumOptions.xAxis.data = stageArr
      this.sumOptions.series[0].data = sumArr
      this.sumChart.setOption(this.sumOptions, {
        lazyUpdate: true
      })
      this.avgOptions.xAxis.data = stageArr
      this.avgOptions.series[0].data = avgArr
      this.avgChart.setOption(this.avgOptions, {
        lazyUpdate: true
      })
    },
    // 完善分析结果
    analyzeResult() {
      Object.keys(this.curIds).forEach(key => {
        const curData = this.curIds[key]
        const preData = this.curIds[+key + 1]
        // console.log(curData)
        // console.log(preData)
        let count = 0
        if (preData) {
          curData.forEach(item => {
            if (preData.includes(item)) {
              count++
            }
          })
          this.$set(this.result[key - 1], 'next', count)
          this.$set(this.result[key - 1], 'precent', (count / this.result[key - 1].over).toFixed(4) * 100 + '%')
        }
      })
      // console.log(this.result)
    },
    handleNodeExpand(node, data) {
      if (!node.icon) {
        this.$set(node, 'icon', 'el-icon-folder-opened')
      } else {
        node.icon = 'el-icon-folder-opened'
      }
    },
    handleNodeCollapse(node, data) {
      node.icon = 'el-icon-folder'
    },
    initSumChart() {
      const sumChart = this.$echarts.init(this.$refs.sumChart)
      this.sumChart = sumChart
      sumChart.setOption(this.sumOptions)
      window.addEventListener('resize', () => {
        sumChart.resize()
      })
    },
    initAvgChart() {
      const avgChart = this.$echarts.init(this.$refs.avgChart)
      this.avgChart = avgChart
      avgChart.setOption(this.avgOptions)
      window.addEventListener('resize', () => {
        avgChart.resize()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/mixin.scss";
.life-container{
  display: flex;
}
.tree-box{
  width: 240px;
  height: calc(100vh - 50px);
  overflow: auto;
  @include borderShadow(0);
  @include scrollBar;
}

.opertions{
  position: relative;
  width: 200px;
  @include borderShadow(0, 4px);
}
.input-box{
  text-align: center;
  @include boxCenter;
}
.num{
  position: absolute;
  top: 35%;
}
.btn{
  font-size: 40px;
  width: 80px;
  height: 80px;
}
.echarts{
  flex: 3;
  @include borderShadow(0);
  .top{
    height: calc(50vh - 25px);
    border-bottom: 1px solid #e7e7e7;
  }
  .bottom{
    height: calc(50vh - 25px);
  }
}
.result{
  height: calc(100vh - 50px) ;
  overflow: auto;
  @include scrollBar;
  padding: 0 5px;
  flex: 2;
  @include borderShadow(0);
}
.sum-chart, .avg-chart{
  width: 100%;
  height: 260px;
}
::v-deep .el-tree-node {
  .is-leaf + .el-checkbox .el-checkbox__inner {
      display:inline-block;
  }
  .el-checkbox__input> .el-checkbox__inner {
      display:none;
  }
}
::v-deep .el-input__inner{
  height: 30px;
}
::v-deep .el-tree-node__expand-icon{
  position: absolute;
  right: 2%;
}
::v-deep .el-collapse{
  background-color: #fff;
}
::v-deep .el-collapse-item{
  padding: 0 10px;
}
</style>
